package com.weepal.pavement.mqtt.demo.ThreadPool;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class DefaultPool {
    public static ThreadPoolExecutor threadPoolExecutor;

    static {
        //获取服务器核心数
        int cores = Runtime.getRuntime().availableProcessors();
        int c = cores / 2;
        //如果是单核或者双核cpu即定长线程池
        //否则取核数的1/2为核心线程数量，全部的核数作为线程池的最大线程数量
        //核心线程数
        int corePoolSize = c == 0 ? cores : c;
        //最大工作线程数
        int maximumPoolSize = c == 0 ? cores : cores;
        //闲暇线程死亡时间  这里是1800秒=30分钟
        long keepAliveTime = 1800;
        //最多容纳100个任务的阻塞队列
        LinkedBlockingQueue<Runnable> blockingQueue = new LinkedBlockingQueue<>(100);
        DefaultPoolFactory defaultPoolFactory = new DefaultPoolFactory();

        threadPoolExecutor = new ThreadPoolExecutor(corePoolSize,maximumPoolSize,keepAliveTime, TimeUnit.SECONDS,
                blockingQueue,defaultPoolFactory,new ThreadPoolExecutor.CallerRunsPolicy());
    }
}
